package edu.zju.gis.dbfg.fileserver.operator;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class LocalFileOperator extends FileOperator {
    //    private  File file;
    private static class InstanceHolder {
        static LocalFileOperator instance = new LocalFileOperator();
    }

    public static LocalFileOperator getInstance() {
        return LocalFileOperator.InstanceHolder.instance;
    }

    @Override
    public boolean exist(String path) {
        return Files.exists(Paths.get(path));
    }

    @Override
    public boolean isDirectory(String path) {
        return Files.isDirectory(Paths.get(path));
    }

    @Override
    public boolean create(String path, boolean isFile) throws IOException {
        File file = new File(path);
        if (isFile)
            return file.createNewFile();
        else
            return file.mkdir();
    }

    @Override
    public boolean deleteFile(String path) throws IOException {
        return Files.deleteIfExists(Paths.get(path));
    }

    @Override
    public boolean rename(File src, File dest) {
        return src.renameTo(dest);
    }

    @Override
    public boolean rename(String src, String dest) {
        return rename(new File(src), new File(dest));
    }

    public boolean upload(OutputStream outputStream, InputStream inputStream) {
        try {
            byte[] buffer = new byte[256];
            int bytesRead = 0;
            while ((bytesRead = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /**
     * 删除路径（文件或目录）
     */
    public void deletePath(String... paths) throws IOException {
        if (paths != null) {
            for (String path : paths)
                deletePath(new File(path));
        }
    }

    @Override
    /**
     * 删除路径（文件或目录）
     */
    public void deletePath(File... paths) throws IOException {
        if (paths != null) {
            for (File path : paths) {
                if (path.exists()) {
                    if (path.isFile())
                        Files.delete(path.toPath());
                    else {
                        File[] subPaths = path.listFiles();
                        if (subPaths != null)
                            for (File subPath : subPaths)
                                deletePath(subPath);
                        Files.delete(path.toPath());
                    }
                }
            }
        }
    }

    @Override
    public void write(String file, Iterable<String> lines) throws IOException {
        write(Paths.get(file), lines);
    }

    /**
     * 覆盖式写入文件
     */
    @Override
    public void write(Path path, Iterable<String> lines) throws IOException {
        Files.createDirectories(path.getParent());
        Files.write(path, lines);
    }

    @Override
    public List<String> getAllFilePaths(String filePath, List<String> filePathList) {
        File[] files = new File(filePath).listFiles();
        if (files == null) {
            return filePathList;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                filePathList.add(file.getPath() + " <------------这是文件夹");
                getAllFilePaths(file.getAbsolutePath(), filePathList);
            } else {
                filePathList.add(file.getPath());
            }
        }

        return filePathList;
    }

    @Override
    public File[] getAllFilePaths(String filePath) {
        File[] files = new File(filePath).listFiles();
        return files;
    }

    @Override
    public void download(String filepath, HttpServletResponse response) {
        try {
            File file = new File(filepath);// 文件
            String filename = file.getName();
            FileInputStream inStream = new FileInputStream(file);
            OutputStream fos = response.getOutputStream();
            byte[] buffer = new byte[1024 * 1024 * 4];
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            response.addHeader("Content-Length", String.valueOf(inStream.available()));
            int length;
            while ((length = inStream.read(buffer)) != -1)
                fos.write(buffer, 0, length);
            inStream.close();
            fos.close();
            return;
        } catch (IOException e) {
//            response.setStatus(500);
            return;
        }
    }

}
